package life.mahu.community.controller;

import com.github.pagehelper.PageInfo;
import life.mahu.community.dto.PageResultDTO;
import life.mahu.community.dto.ResultDTO;
import life.mahu.community.model.Admin;
import life.mahu.community.model.User;
import life.mahu.community.service.AdminService;
import life.mahu.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * user 后台数据控制层
 */
@Controller
@Slf4j
public class AdminUserController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 返回登录页面
     * @return
     */
    @GetMapping("/admin/login")
    public String getlogin(){
        return "admin/login";
    }


    /**
     * 获取当前登录的管理员信息
     * @return
     */
    @GetMapping("/admin/user/getAdminUser")
    @ResponseBody
    public ResultDTO getCurrentAdminUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        Integer id = (Integer) session.getAttribute("isAdminUser");
        //判断session中是否有id，即是否已记住账号
        if (id != null && id != 0) {
            Admin user = adminService.searchUserById(id);
            if (user != null) {
                ResultDTO.okOf(200, "查询成功", user);
            }
        }
        return ResultDTO.errorOf(201, "查无数据！");
    }

    @GetMapping("/admin/checkUserInSession")
    @ResponseBody
    public ResultDTO checkUserInSession(HttpServletRequest request,
                                     HttpServletResponse response){
        UserService userService = new UserService();
        HttpSession session = request.getSession();
        Integer id = (Integer) session.getAttribute("adminUser");
        //判断session中是否有id，即是否已记住账号
        if (id != null && id != 0) {
            Admin user = adminService.searchUserById(id);
            if (user != null) {
                session.setAttribute("isAdminUser", user.getId());
                ResultDTO.okOf(200, "已记住密码！", user);
            }
        }
        return ResultDTO.errorOf(2004, "未记住密码！");
    }

    @GetMapping("/admin/user/list")
    public String getListHtml(){
        return "/admin/user/list";
    }
    @GetMapping("/admin/user/edit")
    public String getEditHtml(Model model,  @RequestParam("id") String id){
        model.addAttribute("userId", id);
        return "/admin/user/edit";
    }
    @GetMapping("/admin/user/detail")
    public String getDetailHtml(Model model,  @RequestParam("id") String id){
        model.addAttribute("userId", id);
        return "/admin/user/detail";
    }

    @GetMapping("/admin/user/add")
    public String getAddHtml(){
        return "/admin/user/edit";
    }

    @ResponseBody
    @GetMapping("/admin/user/delUser")
    public ResultDTO delUser(Model model,  @RequestParam("id") Long id){
        //从服务端查询数据
        Boolean success = userService.delUserById(id);

        if(success){
            return ResultDTO.okOf(200, "删除成功！");
        }else{
            return ResultDTO.okOf(201, "查无数据！");
        }
    }

    @ResponseBody
    @GetMapping("/admin/user/getList")
    public PageResultDTO getUserList(@RequestParam("id") String id,
                                 @RequestParam("name") String name,
                                 @RequestParam("username") String username,
                                 @RequestParam("type") String type,
                                 @RequestParam("limit") Integer limit,
                                 @RequestParam("page") Integer page){

        User user = new User();
        if(!("".equals(id) || id==null)){
            user.setId(Long.parseLong(id));
        }
        if(!("".equals(type) || type==null)){
            user.setType(Integer.parseInt(type));
        }
        if(!("".equals(name) || name==null)){
            user.setName(name);
        }
        if(!("".equals(username) || username==null)){
            user.setUsername(username);
        }

        //List<User> userList = userService.getUserList(user);
        PageInfo userListPage = userService.getUserListPage(user, page, limit);

        return PageResultDTO.okOf(0, "查询成功！", userListPage.getTotal(), userListPage.getList());
    }

    @ResponseBody
    @GetMapping("/admin/user/searchUserDetail")
    public ResultDTO getUserDetail(@RequestParam("id") Long id){

        User user =  userService.getUserById(id);

        return ResultDTO.okOf(user);

    }


    @ResponseBody
    @PostMapping("/admin/user/saveUser")
    public ResultDTO saveUser(HttpServletRequest request, HttpServletResponse response){

        ResultDTO resultDTO = new ResultDTO();
        try {
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            BeanUtils.populate(user, map);
            if(user.getType() == null || user.getType()==0){
                user.setType(1);
            }
            Boolean success = false;
            if(user.getId() == 0 || user.getId() == null){
                success = userService.insertUser(user);
            }else{
                success = userService.updateUserByUserId(user);
            }
            if(success){
                resultDTO.setCode(0);
                resultDTO.setMessage("保存成功！");
            }else{
                resultDTO.setCode(100);
                resultDTO.setMessage("系统繁忙！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultDTO.setCode(101);
            resultDTO.setMessage("服务器出错了！");
        }

        return resultDTO;

    }


    @GetMapping("/admin/user/listAdmin")
    public String getListAdminHtml(){
        return "/admin/user/listAdmin";
    }
    @GetMapping("/admin/user/editAdmin")
    public String getEditAdminHtml(Model model,  @RequestParam("id") String id){
        model.addAttribute("adminId", id);
        return "/admin/user/editAdmin";
    }
    @GetMapping("/admin/user/addAdmin")
    public String getAddAdminHtml(){
        return "/admin/user/editAdmin";
    }


    @ResponseBody
    @GetMapping("/admin/user/delAdminUser")
    public ResultDTO delAdminUser(Model model,  @RequestParam("id") Integer id){
        //从服务端查询数据
        Boolean success = adminService.delAdminUserById(id);
        if(success){
            return ResultDTO.okOf(200, "删除成功！");
        }else{
            return ResultDTO.okOf(201, "查无数据！");
        }
    }

    @ResponseBody
    @GetMapping("/admin/user/getListAdmin")
    public PageResultDTO getUserList(@RequestParam("id") String id,
                                     @RequestParam("userName") String userName,
                                     @RequestParam("limit") Integer limit,
                                     @RequestParam("page") Integer page){

        Admin user = new Admin();
        if(!("".equals(id) || id==null)){
            user.setId(Integer.parseInt(id));
        }
        if(!("".equals(userName) || userName==null)){
            user.setUserName(userName);
        }

        //List<User> userList = userService.getUserList(user);
        PageInfo userListPage = adminService.getAdminUserListPage(user, page, limit);

        return PageResultDTO.okOf(0, "查询成功！", userListPage.getTotal(), userListPage.getList());
    }

    @ResponseBody
    @PostMapping("/admin/user/searchAdminUserDetail")
    public ResultDTO getAdminUserDetail(@RequestParam("id") Integer id){

        Admin user =  adminService.getAdminUserById(id);

        return ResultDTO.okOf(user);

    }


    @ResponseBody
    @PostMapping("/admin/user/saveAdminUser")
    public ResultDTO saveAdminUser(HttpServletRequest request, HttpServletResponse response){

        ResultDTO resultDTO = new ResultDTO();
        try {
            Map<String, String[]> map = request.getParameterMap();
            Admin user = new Admin();
            BeanUtils.populate(user, map);
            Boolean success = false;
            success = adminService.insertUser(user);
            if(success){
                resultDTO.setCode(0);
                resultDTO.setMessage("保存成功！");
            }else{
                resultDTO.setCode(100);
                resultDTO.setMessage("系统繁忙！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultDTO.setCode(101);
            resultDTO.setMessage("服务器出错了！");
        }

        return resultDTO;
    }

    @PostMapping("/admin/user/isExist")
    @ResponseBody
    public ResultDTO checkUserNameIsExit(@RequestParam("userName") String userName) {

        boolean exit=false;
        exit = adminService.isExit(userName);
        if(exit){
            return ResultDTO.errorOf(0, "管理员账号已存在");
        }else{
            return ResultDTO.okOf(200, "该账号名可用！");
        }
    }

    @PostMapping("/admin/doLogin")
    @ResponseBody
    public ResultDTO doLogin(@RequestParam("userName") String userName,
                             @RequestParam("password") String password,
                             @RequestParam("captcha") String captcha,
                             @RequestParam(value = "rememberMe",required = false) String rememberMe,
                             HttpServletRequest request,
                             HttpServletResponse response){

        HttpSession session = request.getSession();
        UserService userService = new UserService();

        if (userName == null || userName.equals("")) {
            ResultDTO.errorOf(2001, "手机不能为空！");
        } else if (password == null || password.equals("")) {
            ResultDTO.errorOf(2002, "密码不能为空！");
        } else if (captcha == null || captcha.equals("")) {
            ResultDTO.errorOf(2003, "验证码不能为空！");
        } else if (captcha != null) {
            String rand = (String) session.getAttribute("rand");
            if (!rand.equals(captcha)) {
                ResultDTO.errorOf(2013, "验证码错误！");
            } else {
                List<Admin> user = adminService.searchAdminUser(userName);
                if (user != null && user.size()!=0&&passwordEncoder.matches(password,user.get(0).getPassword())) {
                    session.setAttribute("isAdminUser", user.get(0).getId());
                    if ("true".equals(rememberMe)) {
                        session.setAttribute("adminUser", user.get(0).getId());
                    }
                }
            }
        }

        return ResultDTO.okOf(200, "登录成功！");
    }

    @GetMapping("/admin/user/loginout")
    public String loginout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("isAdminUser");
        session.removeAttribute("adminUser");
        return "/admin/login";
    }
}
